package com.wwtech.epp.ui.activity.mine.presenter;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;

import com.socks.library.KLog;
import com.wwtech.epp.contain.ContainValue;
import com.wwtech.epp.data.api.HttpAPIWrapper;
import com.wwtech.epp.entity.UserInfo;
import com.wwtech.epp.ui.activity.mine.MyInfoActivity;
import com.wwtech.epp.ui.activity.mine.contract.MyInfoContract;
import com.wwtech.epp.utils.Image.CallBack;
import com.wwtech.epp.utils.Image.ImageTools;
import com.wwtech.epp.utils.ToastUtil;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

import static android.app.Activity.RESULT_OK;


/**
 * @author hzp
 * @Package com.wwtech.epp.ui.activity.mine
 * @Description: presenter of MyInfoActivity
 * @date 2017/08/31 21:07:09
 */
public class MyInfoPresenter implements MyInfoContract.MyInfoContractPresenter{

    HttpAPIWrapper httpAPIWrapper;
    private final MyInfoContract.View mView;
    private CompositeDisposable mCompositeDisposable;
    private MyInfoActivity mActivity;

    public static final int PHOTOZOOM = 0; // 相册/拍照
    public static final int PHOTOTAKE = 1; // 相册/拍照
    public static final int IMAGE_COMPLETE = 2; // 结果

    private String uid;

    File mFile;

    private static final String IMAGE_FILE_LOCATION = "file:///sdcard/temp.jpg";//temp file
    Uri imageUri = Uri.parse(IMAGE_FILE_LOCATION);//The Uri to store the big bitmap

    @Inject
    public MyInfoPresenter(@NonNull HttpAPIWrapper httpAPIWrapper, @NonNull MyInfoContract.View view, MyInfoActivity activity) {
        mView = view;
        this.httpAPIWrapper = httpAPIWrapper;
        mCompositeDisposable = new CompositeDisposable();
        this.mActivity = activity;
    }
    @Override
    public void subscribe() {

    }

    @Override
    public void unsubscribe() {
        if (!mCompositeDisposable.isDisposed()) {
             mCompositeDisposable.dispose();
        }
    }

    @Override
    public void getMyInfo(String uid) {
        Disposable disposable = httpAPIWrapper.getUserInfo(uid)
                .subscribe(new Consumer<UserInfo>() {
                    @Override
                    public void accept(UserInfo user) throws Exception {
                        //isSuccesse
                        KLog.i("onSuccesse");
                        //mView.closeProgressDialog();
//                        ContainValue.loginUserInfo = user.getData();
                        ContainValue.userLogin.getData().setAvatar(user.getData().getAvatar());
                        ContainValue.userLogin.getData().setNickName(user.getData().getNickName());
                        mView.setMyInfo(user.getData());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        //onError
                        KLog.i("onError");
                        throwable.printStackTrace();
                        //mView.closeProgressDialog();
                        //ToastUtil.show(mActivity, mActivity.getString(R.string.loading_failed_1));
                    }
                }, new Action() {
                    @Override
                    public void run() throws Exception {
                        //onComplete
                        KLog.i("onComplete");
                    }
                });
        mCompositeDisposable.add(disposable);
    }

    @Override
    public void setMyInfo(String uid, Map map) {    //RequestBody userId, RequestBody nickName
        mView.showProgressDialog();
        Disposable disposable = httpAPIWrapper.setMyInfo(uid, map)     //userId, nickName
                .subscribe(new Consumer<UserInfo>() {
                    @Override
                    public void accept(UserInfo user) throws Exception {
                        //isSuccesse
                        KLog.i("onSuccesse");
                        mView.closeProgressDialog();
                        getMyInfo(ContainValue.userLogin.getData().getUserId() + "");
//                        mView.setMyInfo(user.getData());
                        ToastUtil.showShort("修改成功");
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        //onError
                        KLog.i("onError");
                        throwable.printStackTrace();
                        mView.closeProgressDialog();
                    }
                }, new Action() {
                    @Override
                    public void run() throws Exception {
                        //onComplete
                        KLog.i("onComplete");
                    }
                });
        mCompositeDisposable.add(disposable);
    }

    @Override
    public void fromCameraUpLoad() {
        AndPermission.with(mActivity)
                .requestCode(PHOTOTAKE)
                .permission(
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA
                )
                .rationale((requestCode, rationale) -> {
                            AndPermission.rationaleDialog(mActivity, rationale).show();
                        }
                )
                .callback(permissionListener)
                .start();
    }

    @Override
    public void fromAlbumUpLoad() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        mActivity.startActivityForResult(intent, PHOTOZOOM);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case PHOTOTAKE://拍照
                if (resultCode == RESULT_OK) {
                    startPhotoZoom(Uri.fromFile(mFile));
                }
                break;
            case PHOTOZOOM:
                if (data == null) {
                    return;
                }
                startPhotoZoom(data.getData());
                break;
            case IMAGE_COMPLETE:
                mView.showProgressDialog();
                Bitmap bitmap = decodeUriAsBitmap(imageUri);
                ImageTools.compressImageByQuality(bitmap, mActivity.getFilesDir() + "/img1.png", new CallBack() {
                    @Override
                    public void onSucess() {
                        KLog.i("图片压缩成功......在回调中打印");
                        mHandler.sendEmptyMessage(0);
                    }
                    @Override
                    public void onFailure() {
                        KLog.i("图片压缩失败,可能是图片不存在......在回调中打印");
                    }
                });
                break;
            default:
                break;
        }
    }
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            mView.closeProgressDialog();
            upLoadImg();
        }
    };

    private void compress() {

    }

    //以bitmap返回格式解析uri
    private Bitmap decodeUriAsBitmap(Uri uri) {
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeStream(mActivity.getContentResolver().openInputStream(uri));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
        return bitmap;
    }

    @Override
    public void upLoadImg() {
        mView.showProgressDialog();
        RequestBody image = RequestBody.create(MediaType.parse("image/png"), new File(mActivity.getFilesDir() + "/img1.png"));
        MultipartBody.Part photo = MultipartBody.Part.createFormData("head", "img1.png", image);
        Disposable disposable = httpAPIWrapper.setMyAvater(uid, photo, RequestBody.create(MediaType.parse("text/plain"), ContainValue.userLogin.getData().getUserId() + ""))     //userId, nickName
                .subscribe(new Consumer<UserInfo>() {
                    @Override
                    public void accept(UserInfo user) throws Exception {
                        //isSuccesse
                        KLog.i("onSuccesse");
                        mView.closeProgressDialog();
                        getMyInfo(ContainValue.userLogin.getData().getUserId() + "");
                        File mFile = new File(mActivity.getFilesDir() + "/img1.jpg");
                        if (mFile.exists()) {
                            mFile.delete();
                        }
                        ToastUtil.showShort(user.getResultMsg());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        //onError
                        KLog.i("onError");
                        throwable.printStackTrace();
                        mView.closeProgressDialog();
                    }
                }, new Action() {
                    @Override
                    public void run() throws Exception {
                        //onComplete
                        KLog.i("onComplete");
                    }
                });
        mCompositeDisposable.add(disposable);
    }

    @Override
    public void setUid(String uid) {
        this.uid = uid;
    }

    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", true);
        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);  //imageurl 文件输出的位置
        intent.putExtra("noFaceDetection", true);
        mActivity.startActivityForResult(intent, IMAGE_COMPLETE);
    }
    private PermissionListener permissionListener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, List<String> grantedPermissions) {
            // 权限申请成功回调。
            if (requestCode == PHOTOTAKE) {
                // TODO ...
                KLog.i("成功的回调");
                Intent intent = new Intent();
                intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
                mFile = new File(Environment.getExternalStorageDirectory(), "DCIM/temp.jpg");
                try {
                    mFile.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //加载Uri型的文件路径
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mFile));
                mActivity.startActivityForResult(intent, PHOTOTAKE);
            }
        }

        @Override
        public void onFailed(int requestCode, List<String> deniedPermissions) {
            // 权限申请失败回调。
            if (requestCode == PHOTOTAKE) {
                // TODO ...
            }
        }
    };
}